from flask import jsonify, render_template, g, redirect, request, current_app

from . import profile_blue
from ... import db
from ...models import News, Category
from ...utils.commons import user_login_data
from ...utils.image_storage import image_upload
from ...utils.response_code import RET
from info.constants import QINIU_DOMIN_PREFIX

'''
获取用户信息首页
请求路径: /user/info
请求方式:GET
请求参数:无
返回值: user.html页面,用户字典data数据
参数解释:
'''


@profile_blue.route("/info")
@user_login_data
def user_index():
    if not g.user:
        return redirect("/")
        # return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    data = {
        "user_info": g.user.to_dict() if g.user else ""
    }
    return render_template("news/user.html", data=data)


'''
获取/设置用户基本信息
请求路径: /user/base_info
请求方式:GET,POST
请求参数:POST请求有参数,nick_name,signature,gender
返回值:errno,errmsg
'''


@profile_blue.route("/base_info", methods=["GET", "POST"])
@user_login_data
def base_info():
    print(request.method)
    if request.method == "GET":
        user_info = g.user.to_dict() if g.user else ""
        print(user_info)
        return render_template("news/user_base_info.html", user_info=user_info)

    if request.method == "POST":
        nick_name = request.json.get("nick_name")
        signature = request.json.get("signature")
        gender = request.json.get("gender")
        print(nick_name, signature, gender)
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        if gender not in ["MAN", "WOMAN"]:
            return jsonify(errno=RET.PARAMERR, errmsg="性别参数错误")
        # 修改用户数据
        g.user.gender = gender
        g.user.signature = signature
        g.user.nick_name = nick_name
        # db.session.
        return jsonify(errno=RET.OK, errmsg="修改成功")


'''
获取/设置,用户头像上传
请求路径: /user/pic_info
请求方式:GET,POST
请求参数:无, POST有参数,avatar
返回值:GET请求: user_pci_info.html页面,data字典数据, POST请求: errno, errmsg,avatar_url
'''


@profile_blue.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_data():
    if request.method == "GET":
        if not g.user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户为登录")
        user_info = g.user.to_dict() if g.user else ""
        print(user_info)
        return render_template("news/user_pic_info.html", user_info=user_info)
    # 发送post请求上传图片
    if request.method == "POST":
        avatar = request.files.get("avatar")
        if not avatar:
            return jsonify(errno=RET.NODATA, errmsg="上传头像为空")
        try:
            image_name = image_upload(avatar.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")

        if not image_name:
            return jsonify(errno=RET.NODATA, errmsg="上传头像失败")

        data = {"avatar_url": QINIU_DOMIN_PREFIX + image_name}
        print("头像：", QINIU_DOMIN_PREFIX + image_name)
        g.user.avatar_url = image_name
        return jsonify(errno=RET.OK, errmsg="上传头像成功", data=data)


'''
获取/设置用户密码
请求路径: /user/pass_info
请求方式:GET,POST
请求参数:GET无, POST有参数,old_password, new_password
返回值:GET请求: user_pass_info.html页面,data字典数据, POST请求: errno, errmsg
POST参数解释:
'''


@profile_blue.route("/pass_info", methods=["GET", "POST"])
@user_login_data
def update_password():
    if not g.user:
        return redirect("/")
    if request.method == "GET":
        return render_template("news/user_pass_info.html")
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if not g.user.check_passowrd(old_password):
        return jsonify(errno=RET.DATAERR, errmsg="旧密码错误")
    g.user.password = new_password
    return jsonify(errno=RET.OK, errmsg="修改成功")


'''
获取新闻收藏列表
请求路径: /user/collection
请求方式:GET
请求参数:p(页数)
返回值: user_collection.html页面
'''


@profile_blue.route("/collection", methods=["GET", "POST"])
@user_login_data
def user_collection():
    if not g.user:
        return redirect("/")
    page = request.args.get("p", 1)
    # print(page)
    if not page:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        pageinate = g.user.collection_news.order_by(News.create_time.desc()).paginate(int(page), 5, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收藏列表失败")
    current_page = pageinate.page
    total_page = pageinate.pages
    items = pageinate.items
    news_list = []
    for item in items:
        news_list.append(item.to_dict())
    print(total_page)
    data = {
        'currentPage': current_page,
        'totalPage': total_page,
        'news_list': news_list
    }
    print(data)
    return render_template("news/user_collection.html", data=data)


'''
获取/设置,新闻发布
请求路径: /user/news_release
请求方式:GET,POST
请求参数:GET无, POST ,title, category_id,digest,index_image,content
返回值:GET请求,user_news_release.html, data分类列表字段数据, POST,errno,errmsg
'''


@profile_blue.route("/news_release", methods=["GET", "POST"])
@user_login_data
def news_release():
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="获取分类列表失败")
        if not categories:
            return jsonify(errno=RET.NODATA, errmsg="分类数据为空")
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        return render_template("news/user_news_release.html", categories=category_list)
    if request.method == "POST":
        print("新闻发布")
        title = request.form.get("title")
        category_id = request.form.get("category_id")
        digest = request.form.get("digest")
        index_image = request.files.get("index_image")
        content = request.form.get("content")
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # 上传图片
        try:
            image_name = image_upload(index_image.read())
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="七牛云异常")

        if not image_name:
            return jsonify(errno=RET.NODATA, errmsg="上传图片失败")
        # 构造新闻属性
        news = News()
        news.title = title
        news.source = g.user.nick_name
        news.content = content
        news.digest = digest
        news.category_id = category_id
        news.user_id = g.user.id
        news.index_image_url = QINIU_DOMIN_PREFIX + image_name
        news.status = 1  # 表示审核中
        # print(news.to_dict())
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="新闻发布失败")

        return jsonify(errno=RET.OK, errmsg="发布成功")


'''
.用户新闻列表
请求路径: /user/news_list
请求方式:GET
请求参数:p
返回值:GET渲染user_news_list.html页面
    '''


@profile_blue.route("/news_list", methods=["GET"])
@user_login_data
def user_news_list():
    if not g.user:
        return redirect("/")
    page = request.args.get("p", 1)
    # print(page)
    if not page:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        pageinate=News.query.filter(g.user.id==News.user_id).order_by(News.create_time.desc()).paginate(int(page), 5, False)
        # pageinate = g.user.collection_news.order_by(News.create_time.desc()).paginate(int(page), 5, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收藏列表失败")
    current_page = pageinate.page
    total_page = pageinate.pages
    items = pageinate.items
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())

    data = {
        'currentPage': current_page,
        'totalPage': total_page,
        'news_list': news_list
    }
    print(data)
    return render_template("news/user_news_list.html",data=data)
'''
获取我的关注
请求路径: /user/user_follow
请求方式: GET
请求参数:p
返回值: 渲染user_follow.html页面,字典data数据
'''

@profile_blue.route("/user_follow", methods=["GET"])
@user_login_data
def user_follow():
    if not g.user:
        return redirect("/")
    page = request.args.get("p", 1)
    # print(page)
    if not page:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        pageinate = g.user.followed.paginate(int(page), 4, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取收藏列表失败")
    current_page = pageinate.page
    total_page = pageinate.pages
    items = pageinate.items
    author_list = []
    for item in items:
        author_list.append(item.to_dict())
    data = {
        'currentPage': current_page,
        'totalPage': total_page,
        'author_list': author_list
    }
    print(data)
    return render_template("news/user_follow.html", data=data)
